package org.layuiframework.stereotype.elasticsearch;

import org.layuiframework.stereotype.exception.APIException;
import org.layuiframework.stereotype.vo.ResultCode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
public class ElasticsearchConfiguration {

    @Bean
    public ElasticsearchHandlers init(List<ElasticsearchHandler> handlers){
        return new ElasticsearchHandlers() {
            @Override
            public Map<String, List<ElasticsearchRecord>> search(ElasticsearchVo vo) {
                Map<String, List<ElasticsearchRecord>> res = new ConcurrentHashMap<>();
                List<CompletableFuture> tasks = new ArrayList<>();
                for (ElasticsearchHandler e : handlers) {
                    if(e.canDeal(vo))
                        tasks.add(CompletableFuture.supplyAsync(() -> {
                            Map<String, List<ElasticsearchRecord>> map = new HashMap<>();
                            map.put(e.getType(), e.deal(vo));
                            return map;
                        }));
                }
                if(tasks.isEmpty()) return null;
                CompletableFuture [] c = new CompletableFuture[tasks.size()];
                CompletableFuture.allOf(tasks.toArray(c)).join();
                tasks.forEach(t -> {
                    try {
                        res.putAll((Map<String, List<ElasticsearchRecord>>)t.get());
                    } catch (Exception e) {
                        throw new APIException(ResultCode.NETERROR, e.getMessage());
                    }
                });
                return res;
            }
        };
    }

}
